/*
 * Random.cpp
 *
 *  Created on: 2009-5-17
 *      Author: thh
 */

#include "Random.h"
#include <openssl/rand.h>
#include "SSLError.h"

namespace Ybdj {

namespace Crypt {

Random::Random() {
}

Random::~Random() {
}

void Random::Clean()
{
	RAND_cleanup();
}
const RAND_METHOD *Random::getMethod()
{
	return RAND_get_rand_method();
}
void Random::setMethod(const RAND_METHOD *method)
{
	RAND_set_rand_method(method);
}
void Random::setMethod(ENGINE *engine)
{
	if(!RAND_set_rand_engine(engine))
		throw SSLError();
}
const RAND_METHOD *Random::getBuiltIn()
{
	return RAND_SSLeay();
}

void Random::Seed(const void *buf, int num)
{
	return RAND_seed(buf,num);
}
void Random::Seed(const void *buf, int num, double entropy)
{
	return RAND_add(buf,num,entropy);
}
bool Random::Status()
{
	return RAND_status()==1;
}
bool Random::Generate(unsigned char *buf,int num)
{
	if(RAND_bytes(buf,num)==1)
		return true;
	throw SSLError();
}
bool Random::GeneratePseudo(unsigned char *buf,int num)
{
	int ret=RAND_pseudo_bytes(buf,num);
	if(ret==-1)
		throw SSLError();
	return ret==1;
}
const char *Random::Path(char *path, long num)
{
	const char *ret = RAND_file_name(path, num);
	if(ret==NULL)
		throw SSLError();
	return ret;
}
int Random::SeedRead(const char *filename, long max_bytes)
{
	return RAND_load_file(filename,max_bytes);
}
int Random::SeedWrite(const char *filename)
{
	int bytes = RAND_write_file(filename);
	if(bytes==-1)
		throw SSLError();
	return bytes;
}

}

}
